package tmp;

import au.id.jericho.lib.html.*;
import java.util.*;
import java.io.*;
import java.net.*;

public class ConvertStyleSheets {
	public static void main(String[] args) throws Exception {
		String sourceUrlString="data/form.html";
		removerCSS(sourceUrlString);
	}
	
	private static void removerCSS(String sourceUrlString) throws Exception {
		if (sourceUrlString.indexOf(':')==-1) 
			sourceUrlString="file:"+sourceUrlString;
		URL sourceUrl=new URL(sourceUrlString);
		Source source=new Source(sourceUrl);
		OutputDocument outputDocument=new OutputDocument(source);
		StringBuffer sb=new StringBuffer();
		List linkStartTags=source.findAllStartTags(Tag.LINK);
		for (Iterator i=linkStartTags.iterator(); i.hasNext();) {
			StartTag startTag=(StartTag)i.next();
			Attributes attributes=startTag.getAttributes();
			String rel=attributes.getValue("rel");
			if (!"stylesheet".equalsIgnoreCase(rel)) 
				continue;
			String href=attributes.getValue("href");
			if (href==null) 
				continue;
			String styleSheetContent;
			try {
				styleSheetContent=Util.getString(new InputStreamReader(new URL(sourceUrl,href).openStream()));
			} catch (Exception ex) {
				System.err.println(ex.toString());
				continue; // don't convert if URL is invalid
			}
			outputDocument.replace(startTag,sb.toString());
		}
		System.err.println("Here is the document "+sourceUrlString+" with all external stylesheets converted to inline stylesheets:\n");
		StringWriter sr = new StringWriter();
		//outputDocument.writeTo(new OutputStreamWriter(System.out));
		outputDocument.writeTo(sr);
		
		System.out.println(sr.toString());

	}
	
}
